from Data import search_file
import win32com.client
from datetime import datetime
import os


def hardware_manual(version_type, is_folder):
    if is_folder:
        filepaths = search_file.select_folder()
    else:
        filepaths = search_file.select_file()
    if filepaths == "-1":
        return "-1"
    for filepath in filepaths:
        if "~" in filepath:
            continue
        # 统一路径分隔符并获取文件名
        filepath = os.path.normpath(filepath)  # 规范化路径
        filename = os.path.basename(filepath)  # 获取文件名

        # 检查文件后缀
        if not filename.lower().endswith(('.doc', '.docx')):
            continue

        try:
            print(f"正在处理：{filename}")
            word = win32com.client.DispatchEx("Word.Application")
            word.Visible = True
            word.DisplayAlerts = False

            # 使用完整路径打开文档
            try:
                doc = word.Documents.Open(os.path.abspath(filepath))
            except Exception as e:
                print(f"无法打开文件，请确保文件路径正确且未被占用: {str(e)}")
                word.Quit()
                del word
                continue

            version = cover_version(doc)
            version_revision = revision_record(doc, version_type)  # 传入版本类型
            version_refresh = refresh_cover(version, version_type, doc, version_revision)

            doc.Save()
            # 确保正确关闭 Word
            doc.Close(SaveChanges=False)
            word.Quit()
            del word
            rename(version_refresh, filepath, filename)
        except Exception as e:
            print(f"处理文件 {filename} 时出错: {str(e)}")
            try:
                doc.Close(SaveChanges=False)
                word.Quit()
                del word
            except:
                pass
            continue
    print("程序执行完成！！！")


def rename(version, filepath, filename):
    if version == "-1":
        return "-1"
    try:
        dirname = os.path.dirname(filepath)
        if "(" in filename and ")" in filename:
            # 处理已有版本号的文件名
            base_name = filename[:filename.rfind('(')]
            # 检查并修正"交换机"和"硬件安装手册"之间的空格
            if "交换机硬件安装手册" in base_name:
                base_name = base_name.replace("交换机硬件安装手册", "交换机 硬件安装手册")
            new_filename = f"{base_name}({version}).docx"
        else:
            # 处理新文件名
            base_name = filename.split("硬件安装手册")[0]
            if base_name.endswith("交换机"):
                base_name = base_name + " "
            new_filename = f'{base_name}硬件安装手册 ({version}).docx'
        new_path = os.path.join(dirname, new_filename)

        # 如果新旧文件名相同，直接跳过
        if os.path.basename(filepath) == new_filename:
            return

        # 检查目标路径是否已存在同名文件
        if os.path.exists(new_path):
            return

        os.rename(filepath, new_path)

    except Exception as e:
        print(f"重命名失败: {str(e)}")


# 获取修订记录版本
def get_word_version(doc):
    try:
        version = doc.Application.Version
        return float(version)
    except:
        return 15.0  # 默认按 Word 2013 处理

def revision_record(doc, version_type=None):
    found_revision = False
    word_version = get_word_version(doc)
    paragraphs_count = doc.Paragraphs.Count
    
    # 遍历文档第50-150段落查找"修订记录"
    if word_version < 16.0:  # Word 2013
        for i in range(50, min(150, paragraphs_count)):
            try:
                if "修订记录" in doc.Paragraphs(i + 1).Range.Text:
                    found_revision = True
                    for j in range(i, min(i + 20, paragraphs_count)):
                        try:
                            current_para = doc.Paragraphs(j + 1)
                            if current_para.Range.Tables.Count > 0:
                                table = current_para.Range.Tables(1)
                                # 获取发布版本号列的数据
                                last_row = table.Rows(table.Rows.Count)
                                release_version = last_row.Cells(3).Range.Text  # 修改为第3列
                                release_version = ''.join(char for char in release_version if char.isprintable())
                                return release_version.strip()
                        except:
                            continue
            except:
                continue
    else:  # Word 2016
        for i in range(50, min(150, paragraphs_count)):
            try:
                if "修订记录" in doc.Paragraphs[i].Range.Text:
                    found_revision = True
                    for j in range(i, min(i + 20, paragraphs_count)):
                        try:
                            if doc.Paragraphs[j].Range.Tables.Count > 0:
                                table = doc.Paragraphs[j].Range.Tables[0]
                                last_row = table.Rows[table.Rows.Count - 1]
                                release_version = last_row.Cells[2].Range.Text
                                release_version = ''.join(char for char in release_version if char.isprintable())
                                return release_version.strip()
                        except:
                            continue
            except:
                continue

    # 只在修订记录版本时输出提示
    if not found_revision and version_type == "修订记录版本":
        print("未找到修订记录表")
    return "-1"

def cover_version(doc):
    word_version = get_word_version(doc)
    version_text = None
    date_text = None
    version = None
    data = None
    version_index = 0
    data_index = 0
    
    if word_version < 16.0:  # Word 2013
        for i in range(min(50, doc.Paragraphs.Count)):
            try:
                text = doc.Paragraphs(i + 1).Range.Text.strip()
                if text:
                    if "文档版本" in text and not version_text:
                        version_text = text
                        version_index = i + 1
                    elif "归档日期" in text and not date_text:
                        date_text = text
                        data_index = i + 1
            except:
                continue
    else:  # Word 2016
        for i in range(min(50, doc.Paragraphs.Count)):
            try:
                text = doc.Paragraphs[i].Range.Text.strip()
                if text:
                    if "文档版本" in text and not version_text:
                        version_text = text
                        version_index = i
                    elif "归档日期" in text and not date_text:
                        date_text = text
                        data_index = i
            except:
                continue

    if not version_text:
        print("未找到文档版本")
    else:
        version = version_text.split('  ')[1].strip()
    if not date_text:
        print("未找到归档日期")
    else:
        data = date_text.split('  ')[1].strip()
    
    return version, data, version_index, data_index

def refresh_cover(value, version_type, doc, version_revision):
    word_version = get_word_version(doc)
    version = None
    if value[0] and value[1]:
        version = value[0]
        data = value[1]
        version_index = value[2]
        data_index = value[3]
        
        if version_type == "封面版本":
            data = datetime.now().strftime('%Y-%m-%d')
        if version_type == "封面版本+1":
            version = f'V{float(version.split("V")[1]) + 0.1}'
            data = datetime.now().strftime('%Y-%m-%d')
        if version_type == "修订记录版本":
            if version_revision == "-1":
                return "-1"
            else:
                data = datetime.now().strftime('%Y-%m-%d')
                version = version_revision

        if word_version < 16.0:  # Word 2013
            # 设置文档版本
            version_para = doc.Paragraphs(version_index)
            version_current_range = version_para.Range
            version_current_range.Text = f'文档版本  {version}\n'
            version_current_range.Style = "封面文档版本"
            
            # 设置归档日期
            data_para = doc.Paragraphs(data_index)
            data_current_range = data_para.Range
            data_current_range.Text = f'归档日期  {data}\n'
            data_current_range.Style = "封面文档版本"
        else:  # Word 2016
            # 设置文档版本
            version_para = doc.Paragraphs[version_index]
            version_current_range = version_para.Range
            version_current_range.Text = f'文档版本  {version}\n'
            version_current_range.Style = "封面文档版本"
            
            # 设置归档日期
            data_para = doc.Paragraphs[data_index]
            data_current_range = data_para.Range
            data_current_range.Text = f'归档日期  {data}\n'
            data_current_range.Style = "封面文档版本"

        # 统一设置缩进
        doc.Application.Selection.HomeKey(Unit=6)  # 移动到文档开头
        doc.Application.Selection.Find.Execute("文档版本")
        doc.Application.Selection.Paragraphs.LeftIndent = 88
        
        doc.Application.Selection.HomeKey(Unit=6)  # 移动到文档开头
        doc.Application.Selection.Find.Execute("归档日期")
        doc.Application.Selection.Paragraphs.LeftIndent = 88
    return version


if __name__ == '__main__':
    # hardware_manual("封面版本", True)
    hardware_manual("修订记录版本", True)
